package com.qingyun.video.utils;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.qingyun.common.exception.ServiceException;
import com.qingyun.common.utils.file.MimeTypeUtils;
import com.qingyun.video.ffmpeg.MultimediaInfo;
import com.qingyun.video.ffmpeg.VideoSize;
import org.apache.commons.lang3.StringUtils;


import java.io.File;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Classname Mp4Utils
 * @Author dyh
 * @Date 2021/9/29 17:19
 */
public class Mp4Utils {

	private static final ExecutorService executor = Executors.newFixedThreadPool(1);

	public static boolean checkFormat(String localPath) {
        Boolean state=false;
		MultimediaInfo videoInfoByFile = null;
		try {
			videoInfoByFile = VideoUtil.getVideoInfoByFile(localPath);
		} catch (Exception e) {
			e.printStackTrace();
			File file = new File(localPath);
			file.delete();
			throw new ServiceException("视频解析错误");
		}
		VideoSize videoSize = videoInfoByFile.getVideo().getSize();
		int width = videoSize.getWidth();
		int height = videoSize.getHeight();
		String rate = checkRate(width,height);
		if (ObjectUtil.isNotNull(rate) && MimeTypeUtils.RATE.containsKey(rate)) {
			state=true;
		} else {
			File file = new File(localPath);
			file.delete();
			throw new ServiceException("视频格式不正确,只能上传16:9或者9:16格式视频");
		}

		//异步插入
		executor.execute(()->{
			transFormation(localPath,rate);
		});

		return state;
	}

	/**
	 * 无脑算法 不用关注
	 * @param width
	 * @param height
	 * @return
	 */
	public static String checkRate(Integer width, Integer height) {
		if (width>height) {
			return "16:9";
		}else{
			return "9:16";
		}
	}


	public static Boolean transFormation(String videoPath,String rate){
		String pathName = StringUtils.substringBefore(videoPath, ".mp4");
		String outPathName=pathName+"_"+System.currentTimeMillis()+"_temp.mp4";
		ConverVideoUtils.beginConver(videoPath,outPathName,rate,true);
		File file = new File(outPathName);
		file.renameTo(new File(videoPath));
		return true;
	}
}
